<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 使用 cache 对 session 进行处理
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: cache.php 11 2012-02-27 03:09:14Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Session_Cache extends Kohana_Session
{

    // Cache instance
    protected $_cache = NULL;

    // The current session id
    protected $_session_id = NULL;

    // The old session id
    protected $_update_id = NULL;

    public function __construct(array $config = NULL, $id = NULL)
    {
        if ( ! isset($config['group']))
        {
            $config['group'] = 'memcache';
        }

        $this->_cache = Cache::instance($config['group']);

        parent::__construct($config, $id);
    }

    public function id()
    {
        return $this->_session_id;
    }

    protected function _read($id = NULL)
    {
        if ( $id OR $id = Cookie::get($this->_name))
        {
            $result = $this->_cache->get($id);

            if (FALSE !== $result)
            {
                // Set the current session id
                $this->_session_id = $this->_update_id = $id;

                // Return the contents
                return $result;
            }
        }

		// Create a new session id
        $this->_regenerate();

        return NULL;
    }

    protected function _regenerate()
    {
        do
        {
            // Create a new session id
            $id = str_replace('.', '', uniqid(NULL, TRUE));

            // Get the the id from the cache
            $result = $this->_cache->get($id);
        }
        while ( ! is_null($result));

        return $this->_session_id = $id;
    }

    protected function _write()
    {
        $this->_cache->set($this->_session_id, $this->__toString(), $this->_lifetime);

        // The update and the session id are now the same
        $this->_update_id = $this->_session_id;

        // Update the cookie with the new session id
        Cookie::set($this->_name, $this->_session_id, $this->_lifetime);

        return TRUE;
    }

    protected function _destroy()
    {
		if ($this->_update_id === NULL)
		{
			// Session has not been created yet
			return TRUE;
		}

        $this->_cache->delete($this->_update_id);

		// Delete the cookie
		Cookie::delete($this->_name);

        return TRUE;
    }

	protected function _restart()
	{
		$this->_regenerate();

		return TRUE;
	}

} // End Session_Cache